package main

import (
	"context"
	"github.com/hpcloud/tail"
	"regexp"
	"time"
)

func ReadPathToChan(ctx context.Context, filename, deviceName, deviceType string, isOk bool, rMonitorStr []string) {
	FileList := []string{}
	MachFile(filename, &FileList)
	if len(FileList) == 0 {
		sugarLogger.Errorf("%s 路径填写有误, 没有匹配到任何文件", filename)
		return
	}
	if isOk {
		for _, file := range FileList {
			sugarLogger.Infof("监听 %s", file)
			go inPutFile2(ctx, file, deviceName, deviceType, rMonitorStr)
		}
	} else {
		for _, file := range FileList {
			sugarLogger.Infof("监听 %s", file)
			go inPutFile1(ctx, file, deviceName, deviceType)
		}
	}
	<- ctx.Done()
	return
}

func inPutFile1(ctx context.Context, filename, deviceName, deviceType string) {
	tails, err := tail.TailFile(filename, tail.Config{
		ReOpen:    true,                                 // 重新打开
		Follow:    true,                                 // 是否跟随
		Location:  &tail.SeekInfo{Offset: 0, Whence: 2}, // 从文件的哪个地方开始读
		MustExist: false,                                // 文件不存在不报错
		Poll:      true,
	})
	if err != nil {
		sugarLogger.Errorf("文件: %s 监听失败, err: %s", filename, err)
		return
	}
	line , ok, esBuffer := &tail.Line{}, true, &EsStruct{}
	for {
		select {
		case line, ok = <-tails.Lines:
			if !ok {
				sugarLogger.Errorf("%s 获取数据失败, err: %s", filename, err)
			}
			esBuffer = &EsStruct{
				Time:       time.Now().UTC().Format(time.RFC3339),
				Address:    FileNames.AddressInfo,
				Devicename: deviceName,
				Devicetype: deviceType,
				Datalog:    line.Text,
			}
			mesChan <- esBuffer
		case <-ctx.Done():
			return
		}
	}
}

func inPutFile2(ctx context.Context, filename, deviceName, deviceType string, rMonitorStr []string) {
	tails, err := tail.TailFile(filename, tail.Config{
		ReOpen:    true,                                 // 重新打开
		Follow:    true,                                 // 是否跟随
		Location:  &tail.SeekInfo{Offset: 0, Whence: 2}, // 从文件的哪个地方开始读
		MustExist: false,                                // 文件不存在不报错
		Poll:      true,
	})
	if err != nil {
		sugarLogger.Errorf("文件: %s 监听失败, err: %s", filename, err)
		return
	}
	line , ok, esBuffer, lenrM, FileRexp := &tail.Line{}, true, &EsStruct{}, len(rMonitorStr), []*regexp.Regexp{}
	//编译FilePath的RMonitorStr正则表达式
	for i:=0; i< lenrM; i++ {
		FileRexp = append(FileRexp, regexp.MustCompile(rMonitorStr[i]))
	}
	for {
		LINE:
		select {
		case line, ok = <- tails.Lines:
			if !ok {
				sugarLogger.Errorf("%s 获取数据失败, err: %s", filename, err)
			}
			esBuffer = &EsStruct{
				Time:       time.Now().UTC().Format(time.RFC3339),
				Address:    FileNames.AddressInfo,
				Devicename: deviceName,
				Devicetype: deviceType,
				Datalog:    line.Text,
			}
			mesChan <- esBuffer
			for i :=0 ; i < lenrM; i++ {
				if FileRexp[i].MatchString(line.Text) {break LINE}
			}
			wechChan <- esBuffer
		case <-ctx.Done():
			return
		}
	}
}